/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.executor;

import java.sql.SQLException;
import java.util.List;

import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.cache.TransactionalCacheManager;
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.transaction.Transaction;

/**
 * @author Clinton Begin
 * @author Eduardo Macarron
 */
public class CachingExecutor implements Executor {

  private final Executor delegate;
  private final TransactionalCacheManager tcm = new TransactionalCacheManager();

  public CachingExecutor(Executor delegate) {
    this.delegate = delegate;
    delegate.setExecutorWrapper(this);
  }

  @Override
  public Transaction getTransaction() {
    return delegate.getTransaction();
  }

  @Override
  public void close(boolean forceRollback) {
    try {
      // issues #499, #524 and #573
      if (forceRollback) {
        tcm.rollback();
      } else {
        tcm.commit();
      }
    } finally {
      delegate.close(forceRollback);
    }
  }

  @Override
  public boolean isClosed() {
    return delegate.isClosed();
  }

  @Override
  public int update(MappedStatement ms, Object parameterObject) throws SQLException {
    flushCacheIfRequired(ms);
    return delegate.update(ms, parameterObject);
  }

  @Override
  public <E> Cursor<E> queryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds) throws SQLException {
    flushCacheIfRequired(ms);
    return delegate.queryCursor(ms, parameter, rowBounds);
  }

  @Override
  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
    /**
     * 获取boudSql对象，包括ognl的解析，包括if where、foreach等的解析都在
     * getBoundSql方法里面处理，这个方法有点复杂，反正就是判断sql是动态sql
     * 还是一般的sql，如果是${}，那么就是动态sql，如果是#{}就是一般的sql，解析的
     * 类都不一样，动态sql是DynamicSqlSource，一般的sql是RawSqlSource
     * 包括if、where、foreach等都是用了不同的类去解析的，mybatis对于动态sql中
     * 每一个标签都使用了不同的类去解析，比如在一个查询中
     * SELECT * FROM USER
     *      <where>
     *          <if test="id != null">
     *              id = #{id}
     *          </if>
     *          <if test="name != null">
     *              and name = #{name}
     *          </if>
     *      </where>
     *      这个where都是单独使用了一个类进行解析的，而且会自动将where后面的
     *      and删除，就是where后面的第一个条件会删除and or 等操作符
     *
     *
     */
    BoundSql boundSql = ms.getBoundSql(parameterObject);
    //创建一级缓存key，一级缓存mybatis是默认开启，没有办法关闭
    CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
    return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

  @Override
  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
    /**
     * 这里的Cache是二级缓存，二级缓存要在mybatis中配置了开启才会使用
     * 也就是说一级缓存默认开启，不能关闭，二级缓存需要手动开启
     * 而在使用的时候先获取二级缓存，如果二级缓存有数据就从二级缓存中获取
     * 每次的查询都会放入一级缓存，满足条件的可以从一级缓存中获取
     *
     * 二级缓存和一级缓存是平级的，Executor有简单、复用、批量的模式，而还有一个带缓存的
     * 也就是CachingExecutor，如果二级缓存开启的话，那么不管是复用的、批量的、还是简单的
     * 都是封装到二级缓存的CachingExecutor中，通过装饰器模式来调用数据库的方法
     * 所以开启了二级缓存，那么就会调用CachingExecutor，如果找不到数据才会去调用创建的执行器delegate
     * 我的这个mybatis版本，二级缓存是默认开启的
     * 二级缓存开启需要配合useCache使用，而只要是select的查询都会默认开启
     * 也就是说针对查询，一级和二级缓存都是默认开启的，先获取二级缓存
     */

    /**
     * cache配合二级缓存使用，也就是说只有在mapper中配置了cache，那么
     * 你开启的二级缓存才会有效果
     * 也就是说开启了cacheEnabled=true并且在mapper中配置了cache并且在select中
     * 配置了useCache才会生效
     * Mybatis.xml:<setting name="cacheEnabled" value="true"/>
     * Mapper.xml:<cache flushInterval="1000"></cache>
     * select:useCache="true"
     * 才会生效二级缓存
     * 如果在select中 配置了flushCache="true"，那么会清空二级缓存
     */
    Cache cache = ms.getCache();
    if (cache != null) {
      //这里是清空缓存，在select等标签中设置了flushCache=true的情况下会清除缓存
      flushCacheIfRequired(ms);
      if (ms.isUseCache() && resultHandler == null) {
        ensureNoOutParams(ms, boundSql);
        @SuppressWarnings("unchecked")
          //从缓存中获取数据，如果数据为空，还是需要去数据库中查询
        List<E> list = (List<E>) tcm.getObject(cache, key);
//        这里满足的是二级缓存，二级缓存有数据就从二级缓存中获取，如果二级缓存中没有，从数据查询出来，然后也会放入二级缓存
        if (list == null) {
          //从数据库中获取
          list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          //查询出来的数据放入二级缓存
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    //如果没有开启二级缓存就从数据库中查询
    return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

  @Override
  public List<BatchResult> flushStatements() throws SQLException {
    return delegate.flushStatements();
  }

  @Override
  public void commit(boolean required) throws SQLException {
    delegate.commit(required);
    tcm.commit();
  }

  @Override
  public void rollback(boolean required) throws SQLException {
    try {
      delegate.rollback(required);
    } finally {
      if (required) {
        tcm.rollback();
      }
    }
  }

  private void ensureNoOutParams(MappedStatement ms, BoundSql boundSql) {
    if (ms.getStatementType() == StatementType.CALLABLE) {
      for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) {
        if (parameterMapping.getMode() != ParameterMode.IN) {
          throw new ExecutorException("Caching stored procedures with OUT params is not supported.  Please configure useCache=false in " + ms.getId() + " statement.");
        }
      }
    }
  }

  @Override
  public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) {
    return delegate.createCacheKey(ms, parameterObject, rowBounds, boundSql);
  }

  @Override
  public boolean isCached(MappedStatement ms, CacheKey key) {
    return delegate.isCached(ms, key);
  }

  @Override
  public void deferLoad(MappedStatement ms, MetaObject resultObject, String property, CacheKey key, Class<?> targetType) {
    delegate.deferLoad(ms, resultObject, property, key, targetType);
  }

  @Override
  public void clearLocalCache() {
    delegate.clearLocalCache();
  }

  private void flushCacheIfRequired(MappedStatement ms) {
    Cache cache = ms.getCache();
    if (cache != null && ms.isFlushCacheRequired()) {
      tcm.clear(cache);
    }
  }

  @Override
  public void setExecutorWrapper(Executor executor) {
    throw new UnsupportedOperationException("This method should not be called");
  }

}
